<?php

abstract class AsyncActivity extends BaseActivity {
	
	private $pidFile;
	public function __construct($activity) {
		parent::__construct($activity);
		$this->pidFile = $this->env['runtime'] . "/{$this->activity['activity_name']}.pid";
	}

	protected function submit() {
		$this->cmd = "nohup {$this->cmd} >{$this->resultPath} 2>{$this->statusPath} & echo $! > {$this->pidFile}";
		return parent::submit();
	}
	
	protected function checkStatus() {
		// check kill command
		$pid = file_get_contents($this->pidFile);
		$pid = trim($pid);
		while($this->isRunning($pid)) {
			sleep(1);
		}
		// get the status after fininsh
		if($this->getStatus()) {
			return true;
		} 
		else {
			$this->setRuntimeInfo(array(
				'state'	=>	TaskState::Failed,
				'message'	=>	"[Async/checkStatus]activity[{$this->activity['activity_name']}] execute failed",
			));
			return false;
		}
	}
	
	protected abstract function getStatus();

	private function isRunning($pid) {
		try {
			$result = shell_exec(sprintf("ps %d", $pid));
			if( count(preg_split("/\n/", $result)) > 2){
				return true;
			}
		}
		catch(Exception $e) {
		}

		return false;
	}
}
